﻿#include "CRobCtrMange.h"

CRobCtrMange::CRobCtrMange(CDevDataBase *pDevDataRob)
{
	m_pDevDataRob = pDevDataRob;
	m_pRobCtrOper = new CRobCtrOper(pDevDataRob);
	m_pMutex = new QMutex(QMutex::Recursive);
	m_pThread = new QThread();
	this->moveToThread(m_pThread);
	connect(m_pThread, SIGNAL(started()), this, SLOT(slot_ThreadWork()));
	m_bhread = false;
}


CRobCtrMange::~CRobCtrMange()
{
	threadStop();
	if (m_pThread != nullptr)
	{
		delete m_pThread;
		m_pThread = nullptr;
	}

	if (m_pRobCtrOper != nullptr)
	{
		delete m_pRobCtrOper;
		m_pRobCtrOper = nullptr;
	}

	if (m_pMutex != nullptr)
	{
		delete m_pMutex;
		m_pMutex = nullptr;
	}
}

void CRobCtrMange::threadRun()
{
	m_pThread->start();
}

void CRobCtrMange::threadStop()
{
	m_bhread = false;
	m_pThread->quit();
	if (!m_pThread->wait(5000))
	{
		m_pThread->terminate();
	}
}

bool CRobCtrMange::ctrDevice(SCtrInfo & stCtrInfo)
{
	if (stCtrInfo.m_bCtrSync == true)
	{
		return m_pRobCtrOper->ctrDevice(stCtrInfo);
	}
	else
	{
		//如果线程没启动 开启线程
		if (!m_bhread)
			threadRun();
		if (m_pMutex->tryLock(3000))
		{
			if (m_vecCtrQueue.size() > 5)
				m_vecCtrQueue.clear();
			//如果是重复命令不添加
			if (m_vecCtrQueue.size() >= 1)
			{
				SCtrInfo stCtrInfoLast = m_vecCtrQueue[m_vecCtrQueue.size() - 1];
				if (stCtrInfo.m_nCtrCmd != stCtrInfoLast.m_nCtrCmd)
				{
					m_vecCtrQueue.push_back(stCtrInfo);
				}
			}
			else
			{
				m_vecCtrQueue.push_back(stCtrInfo);
			}
			m_pMutex->unlock();
			return true;
		}
		else
		{
			return false;
		}
	}
}


void CRobCtrMange::timerEvent(QTimerEvent * event)
{
	if (event->timerId() == m_nGetDevDataTimer)
	{
		m_pRobCtrOper->getRobDevData();//读取机器人数据
	}
	else if (event->timerId() == m_nWriteCsvLogTimer)
	{
		m_pRobCtrOper->writeCsvLog();
	}
}



void CRobCtrMange::slot_ThreadWork()
{
	m_nGetDevDataTimer = startTimer(1000);
	m_nWriteCsvLogTimer = startTimer(1000);
	m_bhread = true;
	while (m_bhread)
	{
		if (!m_bhread)
		{
			killTimer(m_nGetDevDataTimer);
		}
		m_pMutex->lock();
		if (m_vecCtrQueue.size() > 0)
		{
			SCtrInfo stCtrInfo = m_vecCtrQueue[0];
			m_vecCtrQueue.remove(0);
			m_pMutex->unlock();
			m_pRobCtrOper->ctrDevice(stCtrInfo);

		}
		else
		{
			m_pMutex->unlock();
		}
		QEventLoop loop;
		QTimer::singleShot(50, &loop, SLOT(quit()));
		loop.exec();
	}
}
